package com.bum.guru.dj.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.bum.guru.exp.dj.om.Song;

public class SongDAO {
	QueryRunner						queryRunner;

	ResultSetHandler<Song>			beanHandler	= new BeanHandler<Song>(Song.class);
	ResultSetHandler<List<Song>>	listHandler	= new BeanListHandler<Song>(Song.class);

	public boolean add(long id, String name, String url, int catId, Long djId, String trackList, int noHits, int noDowns) throws Exception {
		return queryRunner.update("REPLACE DJ_SONG (ID, NAME, URL, CAT_ID, DJ_ID, TRACK_LIST, NO_HITS, NO_DOWNS) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
				id, name, url, catId, djId, trackList, noHits, noDowns) > 0;
	}

	public boolean add(long id, String name, String url) throws Exception {
		return queryRunner.update("REPLACE DJ_SONG (ID, NAME, URL) VALUES (?, ?, ?)",
				id, name, url) > 0;
	}

	public List<Song> list(int catId, long fromId, int maxResults) throws SQLException {
		String query = "SELECT ID AS id, NAME AS name, URL AS url FROM DJ_SONG ";
		if (0 == fromId) {
			return queryRunner.query(query + " ORDER BY ID DESC LIMIT ? OFFSET 0", listHandler, maxResults);
		}
		return queryRunner.query(query + " WHERE ID<? ORDER BY ID DESC LIMIT ? OFFSET 0", listHandler, fromId, maxResults);
	}

	public Song get(long id) throws Exception {
		return queryRunner.query("SELECT ID AS id, NAME AS name, URL AS url FROM DJ_SONG WHERE ID=?", beanHandler, id);
	}

	public boolean del(long id) throws Exception {
		return queryRunner.update("DELETE FROM DJ_SONG WHERE ID=?", id) > 0;
	}

	public void setQueryRunner(QueryRunner queryRunner) {
		this.queryRunner = queryRunner;
	}
}
